package com.xherorlclass.discovery;

import com.xherorlclass.Constant;
import com.xherorlclass.discovery.impl.NacosRegistry;
import com.xherorlclass.discovery.impl.ZookeeperRegistry;
import com.xherorlclass.exceptions.DiscoveryException;

/**
 * @author ：Xherorl
 * @date ：Created in 2023/8/24 10:10
 * @description：
 */
public class RegistryConfig {

    // 定义连接的 url zookeeper://127.0.0.1:2181  redis://192.168.12.125:3306
    private final String connectionString;

    public RegistryConfig(String connectionString) {
        this.connectionString = connectionString;
    }

    // 可以使用简单工厂完成
    // 返回具体的中心实例
    public Registry getRegistry() {
        // 1、获取注册中心的类型
        String registryType = getRegistryType(connectionString, true).toLowerCase().trim();
        if (registryType.equals("zookeeper")){
            String host = getRegistryType(connectionString, false);
            return new ZookeeperRegistry(host, Constant.TIME_OUT);
        } else if (registryType.equals("nacos")) {
            String host = getRegistryType(connectionString, false);
            return new NacosRegistry(host, Constant.TIME_OUT);
        }
        throw new DiscoveryException("未发现合适的注册中心。");
    }

    private String getRegistryType(String connectionString, boolean isType){
        String[] typeAndHost = connectionString.split("://");

        if (typeAndHost.length != 2){
            throw new RuntimeException("给定的注册中心连接url不合法");
        }
        if (isType){
            return typeAndHost[0];
        }else {
            return typeAndHost[1];
        }

    }
}
